package com.elegant.code.aop.zk;

import com.elegant.code.aop.redission.RedissonProperties;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(RetryPolicy.class)
public class ZooAutoConfiguration {
    @Autowired
    private ZkProperties zkProperties;
    @Bean
    public CuratorFramework zkClient(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zkProperties.getBaseSleepTimeMs(), zkProperties.getMaxRetries());
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkProperties.getAddress(), retryPolicy);
        client.start();
        return client;
    }
    @Bean
    public InterProcessMutex mutex(){
        InterProcessMutex mutex = new InterProcessMutex(zkClient(), zkProperties.getLockPath());
        return mutex;
    }
}
